<template>
  <div :class="$style.root" class="content">
    <div :class="$style.breadcrumb">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item>基础数据</el-breadcrumb-item>
        <el-breadcrumb-item> 工艺路线</el-breadcrumb-item>
        <el-breadcrumb-item>
          <span style="color: #035BEB;"> 资源配置 </span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- <router-link to="/base/processRoute" :class="$style['go-back']">返回</router-link> -->
    <!-- 左侧节点列表 -->
    <div :class="$style['node-list']">
      <div :class="$style['add-node-btn-wrapper']">
        <router-link to="/base/processRoute">
          <el-button :icon="ArrowLeft" :class="$style['ProcessButton']"> 返回</el-button>
        </router-link>
        <el-button @click="showAddNodeDialog" :icon="Plus" :class="$style['ProcessButton']"
                   style="margin-left: 10px"> 新建节点
        </el-button>
        <!-- <el-button @click="showAddNodeDialog" :icon="ArrowLeft" :class="$style['ProcessButton']">
          保存</el-button> -->
      </div>
      <div style="padding: 0 0 10px 20px;font-size: 20px;font-weight: 700">{{ route.query.processName }}</div>
      <draggable v-model="nodes" @change="onDragChange" @end="onDragEnd" animation="200">
        <template #item="{ element, index }">
          <div :key="element.index"
               :style="{ border: activeNodeIndex === index ? '2px solid rgb(44 38 135 / 25%)' : '' }"
               :class="[activeNodeIndex === index ? 'active' : '', $style['node-item']]"
               @click="selectNode(element, index)">
            <div style="display: flex; align-items: center;">
              <div :class="$style['ProcessIcon']">{{ element.index }}</div>
              <span :class="$style['ProcessColor']">{{ element.name }}</span>
            </div>
            <div style="display: flex; align-items: center;">
              <Edit :class="$style['editBUtton']" @click.stop="editData(element, index)"/>
              <!-- <el-button @click="editData(element, index)" :icon="" type="text"
                  :class="$style['ProcessButtonTable']">
                  /el-button> -->
              <Delete :class="$style['delBUtton']" @click.stop="delData(element, index)"/>
              <!-- <el-button @click="delData(element, index)" :icon="Delete" type="text"
                  :class="$style['ProcessButtonTable']">
                  删除</el-button> -->
              <!--							<Operation :class="$style['operaBUtton']" />-->
            </div>
          </div>
        </template>
      </draggable>
    </div>
    <!-- 右侧 Tab 页 -->
    <div :class="$style['right-wrapper']">
      <el-tabs v-if="activeNodeIndex !== null" v-model="activeTab" style="height: 100%">
        <el-tab-pane label="库位" name="1" style="height: 100%">
          <StorageTable :devicesData="devicesData" :onSubmit="onSubmit"/>
        </el-tab-pane>
        <!-- <el-tab-pane label="设备" name="2" style="height: 100%">
          <DeviceTable :devicesData="devicesData" :onSubmit="onSubmit" />
        </el-tab-pane> -->
        <el-tab-pane label="工装" name="3" style="height: 100%">
          <ToolTable :devicesData="devicesData" :onSubmit="onSubmit"/>
        </el-tab-pane>
        <el-tab-pane label="质检" name="4" style="height: 100%">
          <QualityTable :devicesData="devicesData" :onSubmit="onSubmit"/>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 新建节点弹窗 -->
    <el-dialog :title="nowTitle + '节点'" v-model="showNodeDialog">
      <el-form :model="newNode" label-width="100">
        <el-row gutter="10">
          <el-col :span="12">
            <el-form-item label="节点名称">
              <el-input v-model="newNode.name" style="width: 250px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否委外">
              <el-switch v-model="newNode.isOutsourcing"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否追溯">
              <el-switch v-model="newNode.isTraceabilityCode"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工装校验">
              <el-switch v-model="newNode.isTooling"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="newNode.isTraceabilityCode">
            <el-form-item label="追溯规则" required>
              <el-select v-model="newNode.traceCodeStatus" placeholder="请选择" style="width: 250px">
                <el-option v-for="(item, index) in traceCodeStatusList" :key="index" :value="item.id"
                           :label="item.name"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工厂/车间" required>
              <el-select v-model="newNode.organizationId" placeholder="" clearable style="width: 250px">
                <el-option v-for="item in workOptions[0].children" :key="item.id" :label="item.orgName"
                           :value="item.id"></el-option>
              </el-select>
              <!-- <el-tree-select v-model="newNode.organizationId" :data="workOptions" check-strictly
                :render-after-expand="false" :props="{
                  children: 'children',
                  label: 'orgName',
                  value: 'id',
                }" style="width: 300px" /> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="追溯码长度">
              <el-input-number v-model="newNode.traceabilityCodeLength" style="width: 250px"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="showNodeDialog = false">取消</el-button>
        <el-button type="primary" @click="addNode">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import axiosInstance from '@/utils/http/api';
import {ArrowRight, Back, Delete, ArrowLeft, Edit, Operation, Plus} from '@element-plus/icons-vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {ref} from 'vue';
import draggable from 'vuedraggable';
import DeviceTable from './DeviceTable.vue';
import QualityTable from './qualityTable.vue';
import StorageTable from './storageTable.vue';
import ToolTable from './toolTable.vue';
import {lineAll} from '@/api/baseData/productionLine';

import {addProcedureApi, editProcedureApi, productProcedureApi} from '@/api/baseData/process';

const devicesData = ref({});
const route = useRoute();
const shiftData = ref([]);

onMounted(async () => {
  await getData();
});

const workOptions = ref([]);

const getData = async () => {
  workOptions.value = [];
  lineAll({current: 1, pageSize: 100000}).then((res) => {
    if (res.code === 200) {
      workOptions.value = buildTree(res.data.records.map((item) => {
        return {
          ...item.extension,
          ...item
        };
      }));
    }
  });

  // 构建树形结构
  const buildTree = (items) => {
    const itemMap = {};
    const rootItems = [];
    items.forEach((item) => {
      itemMap[item.id] = {...item, name: item.orgName, children: []};
    });
    items.forEach((item) => {
      if (!item.parentId || item.parentId === '0') {
        rootItems.push(itemMap[item.id]);
      } else {
        if (itemMap[item.parentId]) {
          itemMap[item.parentId].children.push(itemMap[item.id]);
        }
      }
    });

    return rootItems;
  };


  await axiosInstance.post('/api/basedataProcedure/getPage', {
    'pageSize': 999,
    'current': 1,
    'processRouteId': route.query.id
  }).then(res => {
    const {code, data, message} = res;
    if (code === 200) {
      const list = data.records.map(element => ({
        ...element,
        name: element.procedureName,
        index: element.index
      }));
      nodes.value = list.sort((a, b) => a.index - b.index);
      shiftData.value = list;
      if (list.length > 0) {
        selectNode(list[0], 0);
      }
    }
  });
};

const delData = (element) => {
  ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await axiosInstance.delete('/api/basedataProcedure/delete', {data: {ids: [element.id]}}).then(res => {
      ElMessage.success('删除成功');
      getData();
    });
  }).catch(() => {
  });
};

const nodes = ref([]);
const nowTitle = ref('新建');
const activeNodeIndex = ref(0);
const activeTab = ref('1');
const showNodeDialog = ref(false);
const newNode = ref({name: '', index: '', devices: []});

const onSubmit = (data, type, sort) => {
  console.log({...devicesData.value, [type]: data, detailID: undefined}, '参数');
  const parentId = devicesData.value.detailID;
  const params = {
    ...parentId,

    configJson: JSON.stringify({...devicesData.value, [type]: data, detailID: undefined})
  };
  if (devicesData.value.addIs) {
    addProcedureApi({...params, procedureId: nodes.value[sort].id}).then(res => {
      if (res.code === 200) {
        ElMessage.success('成功');
        selectNode(nodes.value[sort], sort);
        devicesData.value = {};
      } else {
        ElMessage.warning(res.message);
      }
    });
    return;
  }
  editProcedureApi(params).then(res => {
    if (res.code === 200) {
      ElMessage.success('成功');
      selectNode(nodes.value[sort], sort);
      devicesData.value = {};
    } else {
      ElMessage.warning(res.message);
    }
  });
};

const showAddNodeDialog = () => {
  newNode.value = {name: '', index: '', devices: []};
  nowTitle.value = '新建';
  showNodeDialog.value = true;
};

const addNode = async () => {
  if (newNode.value.isTraceabilityCode) {
    if (!newNode.value.traceCodeStatus) {
      ElMessage.error('请选择追溯规则');
      return false;
    }
  }

  if (!newNode.value.organizationId) {
    ElMessage.error('请选择工厂/车间');
    return false;
  }
  if (newNode.value?.id) {
    await axiosInstance.put('/api/basedataProcedure/update', {
      ...newNode.value,
      procedureName: newNode.value.name,
      index: newNode.value.index,
      processRouteId: route.query.id,
      id: newNode.value.id,
      traceabilityCodeLength: newNode.value.traceabilityCodeLength
    });
  } else {
    await axiosInstance.post('/api/basedataProcedure/save', {
      procedureName: newNode.value.name,
      processRouteId: route.query.id,
      index: nodes.value.length + 1,
      isTraceabilityCode: newNode.value.isTraceabilityCode,
      isTooling: newNode.value.isTooling,
      traceCodeStatus: newNode.value.traceCodeStatus,
      isOutsourcing: newNode.value.isOutsourcing,
      organizationId: newNode.value.organizationId,
      traceabilityCodeLength: newNode.value.traceabilityCodeLength
    });
  }
  ElMessage.success('成功');
  showNodeDialog.value = false;
  getData();

};

const selectNode = (element, index) => {
  productProcedureApi({procedureId: element.id}).then(res => {
    if (res.data.records.length > 0) {
      const configJson = JSON.parse(res.data.records[0].configJson);
      nodes.value[index].devices = configJson;
      devicesData.value = {...configJson, index, detailID: res.data.records[0], addIs: false};
    } else {
      nodes.value[index].devices = {};
      devicesData.value = {addIs: true, index};
    }
  });
  activeNodeIndex.value = index;
};

const editData = (element, index) => {
  nowTitle.value = '编辑';
  newNode.value = {...element, code: index};
  showNodeDialog.value = true;
};

const onDragEnd = () => {
  updateIndexes();
};

const onDragChange = (event) => {
  const {oldIndex, newIndex} = event.moved;
  if (oldIndex !== newIndex) {
    // updateIndexes(oldIndex, newIndex);
  }
};

const traceCodeStatusList = ref([
  {
    id: 'NOYEARWEEKDAY',
    name: '模具号年月日'
  }, {
    id: 'PLATING_TTACEABILITYCODE',
    name: '电镀'
  }
]);

// 更新数据库中的 index 值
const updateIndexes = async (oldIndex?: number, newIndex?: number) => {
  const sortedNodes = [...nodes.value];
  if (oldIndex !== undefined && newIndex !== undefined) {
    const movedNode = sortedNodes.splice(oldIndex, 1)[0];
    sortedNodes.splice(newIndex, 0, movedNode);
  }
  sortedNodes.forEach((node, index) => {
    node.index = index + 1;
  });
  const sortedNodesFeature = sortedNodes.map(element => {
    return {
      id: element.id,
      index: element.index
    };
  });
  await axiosInstance.post('/api/basedataProcedure/queryIndexOrder', sortedNodesFeature);
};
</script>
<style lang="scss" module>
.root {
  display: flex;
  width: 100%;
  height: calc(100%);
  box-sizing: border-box;
  border-bottom: 1px solid #eaeaea;
  position: relative;

  .breadcrumb {
    position: absolute;
    top: -30px;
    left: 0px;
    margin: 5px;

    span {
      font-size: 15px;
      color: #828282;
    }
  }

  .node-list {
    width: 400px;
    height: 100%;
    box-sizing: border-box;
    box-shadow: 0px 4px 4px 0px rgba(0, 20, 45, 0.04);
    background-color: #fff;
    border-radius: 10px;
    overflow: auto;

    .add-node-btn-wrapper {
      display: flex;
      justify-content: flex-end;
      position: sticky;
      top: 0;
      background-color: #ffff;
      padding: 10px
    }

    .node-item {
      display: flex;
      // justify-content: space-between;
      box-sizing: border-box;
      padding: 10px;
      margin: 10px;
      color: #fff;
      background-color: #eaeaea;
      cursor: move;
      user-select: none;
      border-radius: 5px;
      background-image: url('@/assets/images/routerBg.png');
      /* 拖拽指示器颜色 */

      font-weight: bolder;
      height: 84px;
      align-items: center;


    }
  }

  .right-wrapper {
    width: calc(100% - 410px);
    box-shadow: 0 4px 4px 0 rgba(0, 20, 45, 0.04);
    background-color: #fff;
    border-radius: 10px;
    margin-left: 10px;
    padding: 0 20px 20px 20px;
    box-sizing: border-box;
    height: 100%;

  }


}

.elTab {
  height: 100%;
  overflow: auto;
}

.node-item.active {
  background-color: #409eff;
  color: #fff;
}

.node-item {
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 10px;
  margin: 10px;
  color: #333;
  background-color: #f8f8f8;
  cursor: move;
  user-select: none;
  border-radius: 20px;
  transition: all 0.3s ease;
}

.node-item.active {
  background-color: #409eff;
  color: #fff;
}

.ProcessButton {
  width: 108px;
  height: 32px;
  border-radius: 3px;
  box-sizing: border-box;
  border: 1px solid #035BEB;
  background: #fff;
  color: #035BEB;


}

.ProcessButtonTable {
  width: 80px;
  height: 32px;
  border-radius: 3px;
  box-sizing: border-box;
  border: 1px solid #fff;
  // background: #fff;
  color: #fff;
}

.ProcessIcon {
  height: 42px;
  width: 34px;
  background-image: url(/src/assets/images/logoRouter.png);
  background-size: 100%;
  color: #fff;
  background-repeat: no-repeat;
  margin-left: 10px;
  text-align: center;
  line-height: 38px;
  font-weight: bold;

}

.ProcessColor {
  font-size: 14px;
  font-weight: bold;
  color: #000E1F;
  margin-left: 15px;
}

.editBUtton {
  height: 19px;
  color: #035BEB;
  margin-right: 15px;
  cursor: pointer;

}

.delBUtton {
  height: 19px;
  color: red;
  margin-right: 15px;
  cursor: pointer;

}

.operaBUtton {
  color: #ffffff;
  height: 20px;
  font-weight: bolder;
  cursor: pointer;
}
</style>
